package com.meeting.config;

import com.meeting.utils.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * JWT拦截器，用于验证请求中的JWT令牌
 */
@Component
public class JwtInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 从请求头中获取token
        String token = request.getHeader("Authorization");

        // 放行登录接口
        // if (request.getRequestURI().contains("/auth/login") ) {
        //     return true;
        // }
        
        // 验证token
        if (token != null ) {
            if (JwtUtil.validateToken(token)) {
                return true;
            }
        }
        
        // 如果验证失败，返回401错误
        response.setContentType("application/json;charset=UTF-8");
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.getWriter().write("{\"code\":401,\"success\":false,\"message\":\"未授权，请先登录\"}");
        return false;
    }
}